package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.entity.Purchase;
import com.antdesignbackend.backend.entity.entityVo.ProductionVo;
import com.antdesignbackend.backend.entity.entityVo.PurchaseVo;
import com.antdesignbackend.backend.service.PurchaseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/purchase")
@Controller
public class PurchaseController extends BaseController {

    @Autowired
    PurchaseService purchaseService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;

    @GetMapping("/index")
    @AuthToken
    public String ProductionIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "records/purchase/index";
    }

    /**
     * 分页查询
     * @param
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody PurchaseVo purchaseVo) {
        ReturnVO result = new ReturnVO();
        List<PurchaseVo> datalist=new ArrayList<>();
        try {
            //拿到当前日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date = sdf.format(new Date());
            QueryWrapper<PurchaseVo> queryWrapper = new QueryWrapper<>();
            if (purchaseVo.getPurchaseName() != null && !purchaseVo.getPurchaseName().equals("")){
                queryWrapper.like("purchaseName",purchaseVo.getPurchaseName());
            }
            if (purchaseVo.getType() != null){
                if (purchaseVo.getType() == 1){ //未过期
                    queryWrapper.ge("EffectiveTime",date);
                }else {
                    queryWrapper.lt("EffectiveTime",date);
                }
            }
            if (purchaseVo.getTimeInterval() != null && !purchaseVo.getTimeInterval().equals("")){
                String[] str=purchaseVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("purchaseTime",star,end);
            }
            queryWrapper.orderByDesc("purchaseTime").orderByDesc("a.createTime");
            queryWrapper.eq("a.eid",getLoginEnterpriseId());
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=purchaseService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= purchaseService.search(queryWrapper,new Page<>(purchaseVo.getPageIndex(),purchaseVo.getPageSize()));
                for (PurchaseVo purchaseVo1:datalist){
                    if (purchaseVo1.getEffectiveTime() == null){
                        purchaseVo1.setType(0);
                        continue;
                    }
                    if (purchaseVo1.getEffectiveTime().before(sdf.parse(date)))
                        purchaseVo1.setType(0);
                    else
                        purchaseVo1.setType(1);
                }
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    @PostMapping("/tableSearchMe/{eid}")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearchMe(@PathVariable("eid") int eid) {
        ReturnVO result = new ReturnVO();
        List<PurchaseVo> datalist=new ArrayList<>();
        try {
            //拿到当前日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date = sdf.format(new Date());
            QueryWrapper<PurchaseVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("purchaseTime");
            queryWrapper.eq("a.eid",eid);

            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=purchaseService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= purchaseService.search(queryWrapper,new Page<>(1,10));
                for (PurchaseVo purchaseVo1:datalist){
                    if (purchaseVo1.getEffectiveTime() == null){
                        purchaseVo1.setType(0);
                        continue;
                    }
                    if (purchaseVo1.getEffectiveTime().before(sdf.parse(date)))
                        purchaseVo1.setType(0);
                    else
                        purchaseVo1.setType(1);
                }
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     * 查询所有
     * @param
     * @return
     */
    @PostMapping("/selectAll")
    @ResponseBody
    @AuthToken
    public ReturnVO selectAll() {
        ReturnVO result = new ReturnVO();
        try {
            QueryWrapper<Purchase> purchaseQueryWrapper=new QueryWrapper<>();
            purchaseQueryWrapper.eq("eid",getLoginEnterpriseId());
            purchaseQueryWrapper.groupBy("purchaseName");
            //拿到当前日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date = sdf.format(new Date());
            purchaseQueryWrapper.ge("EffectiveTime",date);
            List<Purchase> datalist=purchaseService.list(purchaseQueryWrapper);
            List<String> strings=new ArrayList<>();
            for(Purchase purchase:datalist){
                strings.add(purchase.getPurchaseName());
            }
            result.setData(strings);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * 下拉选联动查询
     * @return
     */
    @PostMapping("/selectManufacturer/{varietyName}")
    @ResponseBody
    @AuthToken
    public ReturnVO selectManufacturer(@PathVariable("varietyName") String varietyName) {
        System.out.println("进入下拉选联动查询"+varietyName);
        ReturnVO result = new ReturnVO();
        try {
            QueryWrapper<Purchase> purchaseQueryWrapper=new QueryWrapper<>();
            purchaseQueryWrapper.eq("eid",getLoginEnterpriseId());
            purchaseQueryWrapper.eq("purchaseName",varietyName);
            //拿到当前日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date = sdf.format(new Date());
            purchaseQueryWrapper.ge("EffectiveTime",date);
            List<Purchase> datalist=purchaseService.list(purchaseQueryWrapper);
            List<String> strings=new ArrayList<>();
            for(Purchase purchase:datalist){
                strings.add(purchase.getManufacturer());
            }
            result.setData(strings);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody Purchase purchase) throws Exception {
        ReturnVO result = new ReturnVO();
        boolean b = false;
        //计算有效时间
        Date effectiveTime = CalendarDate.addDate(purchase.getPurchaseTime(),"day",purchase.getEffective());
        purchase.setEffectiveTime(effectiveTime);
        if(purchase.getPurchaseId()==null || purchase.getPurchaseId()==0){
            purchase.setUid(getLoginUserId());
            purchase.setCreateTime(new Date());
            purchase.setEid(getLoginEnterpriseId());
            b=purchaseService.save(purchase);
        }else{
            b=purchaseService.updateById(purchase);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 删除
     * @param
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        ReturnVO result = new ReturnVO();
        if (purchaseService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
        } else {
            result.setMessage("删除失败");
            result.setCode("0");
        }
        return result;
    }
}
